package exec;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Message {
    public final static byte CONNECT = 0, DISCONNECT = 1, MESSAGE = 2, LIST = 3, FILENAME = 4, FILESIZE = 5, FILE_CHUNK = 6, WRITING = 7, NOT_WRITING = 8;
    /*
     * 0 ==> CONNECT
     * 1 ==> DISCONNECT
     * 2 ==> MESSAGE
     * 3 ==> LIST
     * 4 ==> FILENAME
     * 5 ==> FILESIZE
     * 6 ==> FILE_CHUNK
     * 7 ==> WRITING
     * 8 ==> NOT_WRITING
     */
    private byte type;
    private String nickSrc;
    private String nickDest;
    private byte[] data;

    Message() {
    }
    
    public byte getType() {
        return this.type;
    }
    
    public byte[] getData() {
        return this.data;
    }
    
    public String getNickSrc() {
        return this.nickSrc;
    }
    
    public String getNickDest() {
        return this.nickDest;
    }
    
    // sending purpose
    public Message(byte type, String src, String dest, String data) {
        this.type = type;
        nickSrc = src;
        nickDest = dest;
        this.data = data.getBytes();
    }
    
    public Message(byte type, String src, String dest, byte[] data) {
        this.type = type;
        nickSrc = src;
        nickDest = dest;
        this.data = data;
    }
    
    // collecting purpose
    public void send(DataOutputStream outputStream) {
        try {
            outputStream.write(type);
            outputStream.writeUTF(nickSrc);
            outputStream.writeUTF(nickDest);
            outputStream.writeInt(data.length);
            outputStream.write(data);
        } catch (IOException ex) {
            Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }
    
    public void read(DataInputStream inputStream) {
        try {
            type = inputStream.readByte();
            nickSrc = inputStream.readUTF();
            nickDest = inputStream.readUTF();
            data = new byte[inputStream.readInt()];
            inputStream.read(data);
            if (type == CONNECT || type == DISCONNECT)
                System.out.println(nickSrc + " : " + new String(data));
        }
        catch (IOException ex) {
            Logger.getLogger(Message.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}

